package com.demo.blog.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    //密钥
    public static String secret = "fVQWqBNI8mA1OBos95ebw9w4VwfIOlHIJCFLbskeczs=";

    //过期时间
    public static long expiration = 1000 * 60 * 60 * 24 * 7; //24小时

    //生成安全密钥(加工密钥) 签名
    private static SecretKey secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

    /*
    * 生成密钥*/
    public static String genJwt(Map<String, Object> claims) {
        //生成密钥
        String jwt = Jwts.builder()
                .setClaims(claims)   //自定义内容 (载荷)
                .setIssuedAt(new Date()) //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration)) //设置过期时间
                .signWith(secretKey) //签名
                .compact();
        return jwt;
    }

    /*
    * 验证密钥
    * */
    public static Claims parseJwt(String jwt) {
        if (!StringUtils.hasLength(jwt)) {
            return null;
        }

        //创建解析器，解析密钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(secretKey); //解析器明确签名
        Claims claims = null;
        try {
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
            log.error("解析令牌失败,jwt:{}", jwt);
        }
        return claims;
    }

    //获取用户ID
    public static Integer getUserIdFromToken(String jwtToken) {
        Claims claims = JwtUtils.parseJwt(jwtToken); //解析令牌
        if (claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (Integer) userInfo.get("userId");
        }
        return null;
    }

}
